package no.kolstad.movies.model;
/**
 *  Copyright [2008] Christopher Kolstad
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software distributed under the License 
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License. 
 */
import java.io.Serializable;

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
 * Base class for Model objects. Contains standard implementations of toString,
 * equals and hashCode.
 */
public abstract class BaseModelObject implements Serializable {
  /**
   * Returns the (preferably synthetic) id of this object.
   * 
   * @return the id of this object.
   */
  public abstract Long getId();

  public String toString() {
    return ToStringBuilder.reflectionToString(this,
        ToStringStyle.MULTI_LINE_STYLE);
  }

  /**
   * Compares this object to the passed-in one.
   * <p>
   * This implementation compares for identity ({@code ==}), then returns
   * {@code false} if the passed-in object is {@code null}, of a different
   * class than this object, or if the passed-in object has a {@code null} id.
   * <p>
   * Finally, the id of this object is compared to that of the object passed in.
   * 
   * @param o
   *          an {@code Object}
   * @return {@code true} if the passed-in object is equal to this one
   */
  public boolean equals(Object o) {
    if (this == o)
      return true;

    if (o == null || !o.getClass().equals(this.getClass())
        || this.getId() == null)
      return false;

    return this.getId().equals(((BaseModelObject) o).getId());
  }

  /**
   * Builds a hash code using {@link HashCodeBuilder}, using the superclass
   * hash code and this object's id.
   * 
   * @return a hash code for this object.
   */
  public int hashCode() {
    return new HashCodeBuilder(17, 37).appendSuper(super.hashCode()).append(
        getId()).toHashCode();
  }
  
}

